import base64
import re
import pandas as pd

import requests

username = 'script'
password = '123456a.'

bct_url = "http://10.1.6.47"

user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36 Edg/97.0.1072.69 '


def login(username: str, password: str, host: str, port: int, method: str = None) -> dict:
    """
    登陆 - 获取token
    :param username: 登陆用户名
    :param password: 登陆密码
    :param host: 服务器地址
    :param port: 服务器端口
    :param method: 如果设为base64的话，会对用户名密码进行base64
    :return: 登陆头，包含了访问所需的token
    """
    url = '%s/auth-service/users/login' % url_builder(host, port)
    user = username
    pwd = password
    print("login with %s" % (user))
    if method == 'base64':
        user = base64.b64encode(username.encode(encoding='utf-8')).decode(
            encoding='utf-8')
        pwd = base64.b64encode(password.encode(encoding='utf-8')).decode(encoding='utf-8')
    body = {
        'username': user,
        'password': pwd
    }
    res = requests.post(url, json=body)
    try:
        json = res.json()
        print("login success")
        print("token:%s" % json['result']['token'])
    except Exception as e:
        print(e)
        print('\t=>' + res.text)
        print(res.headers)
        raise RuntimeError('error logging in: ')
    if 'error' in json:
        raise RuntimeError('error logging in: ' + json['error']['message'])
    token = json['result']['token']
    headers = {
        'Authorization': 'Bearer ' + token
    }
    return headers


def _get_token(auth_username: str, auth_password: str, server_url: str,
               base64_encode: bool = True) -> str:
    auth_url = "%s%s" % (server_url, '/api/auth-service/users/login')

    if base64_encode:
        usr_name = base64.b64encode(auth_username.encode())
        usr_pwd = base64.b64encode(auth_password.encode())
    else:
        usr_name = auth_username
        usr_pwd = auth_password

    auth_body = {
        'userName': usr_name.decode(),
        'password': usr_pwd.decode()
    }
    headers = {'User-Agent': user_agent}
    auth = requests.post(auth_url, json=auth_body, headers=headers)
    try:
        _token = auth.json()['token']
        return _token
    except Exception:
        error_message = auth.json()['errorMessage']
        raise ValueError(error_message)


def url_builder(host: str, port: int = 80) -> str:
    """
    按照host和port构建一个标准url
    :param host:
    :param port:
    :return:
    """
    protocol_prefix = re.match(r'^(http|https)://[^\n\r]+', host)
    if protocol_prefix:
        return '%s:%s' % (host, port)
    else:
        protocol = 'http'
        if port == 443:
            protocol = 'https'
        return '%s://%s:%s' % (protocol, host, port)


if __name__ == '__main__':
    token = _get_token(username, password, bct_url)

    # todo
    df = pd.read_excel('tmp.xlsx')
    excel_data = []
    head_list = ['orgNumber','orgName']
    for i in df.values:
        a_line = dict(zip(head_list, i))
        excel_data.append(a_line)
    headers = {"Authorization": "Bearer " + token}

    param1 = {"page": 0, "pageSize": 10000, "saleIsolation": True,
              "containUnownedByIsolation": True}
    # 获得json 数据
    r = requests.post(url=bct_url + "/bct/reference-data-service/institution/page",
                      json=param1, headers=headers)
    all_org = r.json().get('page')
    for org in all_org:
        id = org.get("id")
        param_id = {"id": id}
        r_id = requests.post(
            url=bct_url + "/bct/reference-data-service/institution/find-by-id",
            json=param_id, headers=headers)
        result_id = r_id.json()
        org_number = result_id['institutionBasicInfoGroup']['orgNumber']
        for data in excel_data:
            if data.get('orgName') == result_id['institutionBasicInfoGroup']['orgName']:
                result_id['institutionBasicInfoGroup']['orgNumber'] = data.get('orgNumber')
                requests.post(
                    url=bct_url + "/bct/reference-data-service/institution/update",
                    json=result_id, headers=headers)
                break
